import { ChatGPTAPI } from "chatgpt";
import http from "http";
http
  .createServer((req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*"); //设置响应头解决跨域
    if (req.url !== "/sendMsg") return sendRes(res, "not find", 404);
    let _data = "";
    req.on("data", (d) => {
      _data += d;
    });
    req.on("end", () => {
      const data = JSON.parse(_data);
      sendChatGPTMsg(data)
        .then((r) => {
          sendRes(res, JSON.stringify({ msg: r }));
        })
        .catch((err) => {
          sendRes(res, JSON.stringify(err));
        });
    });
  })
  .listen(4096, () => {
    console.log("服务开启！");
  });
/**
 * @name:
 * @description: 服务端响应消息
 * @param {ServerResponse} res ServerResponse实例
 * @param {*} msg 发送的消息
 * @param {*} code 状态码
 * @return {*}
 */
const sendRes = (res, msg = "", code = 200) => {
  res.writeHead(code, {
    "Content-Type": "text/plain",
    "Access-Control-Allow-Origin": "*",
  });
  res.write(msg);
  res.end();
};
/**
 * @name:
 * @description: 封装了一下ChatGPT
 * @param {*} msg 发送的消息
 * @param {*} sessionToken 浏览器cookie拿到的令牌
 * @return {Promise}
 */
const sendChatGPTMsg = async ({ msg, apiKey }) => {
  const { promise, resolve, reject } = defer();
  const api = new ChatGPTAPI({
    apiKey,
    markdown: false,
  });
  api.sendMessage(msg).catch(reject).then(resolve);
  return promise;
};
/**
 * @name:
 * @description: promise扁平处理
 * @return {*}
 */
const defer = () => {
  let resolve, reject;
  return {
    promise: new Promise((_resolve, _reject) => {
      resolve = _resolve;
      reject = _reject;
    }),
    resolve,
    reject,
  };
};
